package com.begye.smartloan.apptest.renzheng.document

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.begye.smartloan.apptest.MyApplication
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.doImageUpload
import com.begye.smartloan.apptest.tool.doPostRequest
import com.util.utillib.util.imagecovert.ImageConvert
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class RenZhengDocumentViewModel : ViewModel() {

    var pageTag: String = ""

    var documentType: Int = 0
    var documentPosition: Int = 0

    var documentIdCardFrontUrl: String = ""
    var documentIdCardBackUrl: String = ""

    var documentDrivingFrontUrl: String = ""
    var documentDrivingBackUrl: String = ""

    var documentPassportUrl: String = ""

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    private val _saveDocumentSuccessStateLiveData = MutableLiveData<Boolean>()
    val onSaveDocumentSuccessStateLiveData get() = _saveDocumentSuccessStateLiveData


    fun handleTakePictureResult(
        result: String?,
        onConversionCompleted: (Int, Bitmap?, Int) -> Unit,
        onUploadCompleted: (Int, String?, Int) -> Unit
    ) {
        try {
            println(result.toString())

            result?.let {
                val localPath = it
                val thumpImg = imagePathToBitmap(localPath)
                onConversionCompleted.invoke(documentType, thumpImg, documentPosition)
                requestUploadImage(localPath, documentType, documentPosition, onUploadCompleted)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("Recycle")
    fun handlePhotoAlbumResult(
        context: Context,
        result: Uri?,
        onConversionCompleted: (Int, Bitmap?, Int) -> Unit,
        onUploadCompleted: (Int, String?, Int) -> Unit
    ) {
        try {
            println(result.toString())
            result?.let {
                val path = imageUriToLocalFile(context, it)
                //压缩图片
                ImageConvert.startConvertImage(context, File(path)) { localPath, thumpImg ->
                    onConversionCompleted.invoke(documentType, thumpImg, documentPosition)
                    localPath?.let {
                        requestUploadImage(
                            localPath,
                            documentType,
                            documentPosition,
                            onUploadCompleted
                        )
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun imageUriToLocalFile(
        context: Context,
        contentURI: Uri
    ): String {
        try {
            println(contentURI.path)

            val imgDir = "${context.filesDir}${File.separator}${MyApplication.product}_TEMP_PICS"
            val dirFile = File(imgDir)
            if (!dirFile.exists()) {
                dirFile.mkdirs()
            }

            val outFilePath = "$imgDir${File.separator}${System.currentTimeMillis()}.jpg"
            val imgInputStream: InputStream =
                context.contentResolver.openInputStream(contentURI) ?: return ""
            val outFile = File(outFilePath)
            val buffer = ByteArray(1024)
            var len: Int
            val fos = FileOutputStream(outFile)
            while (imgInputStream.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            imgInputStream.close()
            return outFilePath
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun imagePathToBitmap(filePath: String?): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePath, options)
    }

    fun canSubmit(): Boolean {
        if (documentType == 0) {
            if (documentIdCardFrontUrl.isBlank() || documentIdCardBackUrl.isBlank()) {
                return false
            }
        } else if (documentType == 1) {
            if (documentDrivingFrontUrl.isBlank() || documentDrivingBackUrl.isBlank()) {
                return false
            }
        } else {
            if (documentPassportUrl.isBlank()) {
                return false
            }
        }
        return true
    }

    fun requestSaveDocument() {
        val params = hashMapOf<String, Any>()
        if (documentType == 0) {
            params["cardImgUrl"] = documentIdCardFrontUrl
            params["cardBackImgUrl"] = documentIdCardBackUrl
            params["cardType"] = "IDCARD"

        } else if (documentType == 1) {
            params["cardImgUrl"] = documentDrivingFrontUrl
            params["cardBackImgUrl"] = documentDrivingBackUrl
            params["cardType"] = "DRIVING"

        } else {
            params["cardImgUrl"] = documentPassportUrl
            params["cardType"] = "PASSPORT"
        }

        doPostRequest(
            path = "G3CHffCsfqAmblu3rNCiLA",
            action = params,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    _saveDocumentSuccessStateLiveData.value = true
                }

                override fun onApiError(code: String, errMsg: String) {
                }
            })
    }

    private fun requestUploadImage(
        filePath: String,
        type: Int,
        position: Int,
        onFinished: (Int, String?, Int) -> Unit
    ) {
        doImageUpload(
            filePath = filePath,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    val url = jsonObject.optString("url", "")
                    if (url.isNotBlank()) {
                        if (type == 0) {
                            if (position == 0) {
                                documentIdCardFrontUrl = url
                            } else {
                                documentIdCardBackUrl = url
                            }
                        } else if (type == 1) {
                            if (position == 0) {
                                documentDrivingFrontUrl = url
                            } else {
                                documentDrivingBackUrl = url
                            }
                        } else if (type == 2) {
                            documentPassportUrl = url
                        }

                        onFinished.invoke(type, url, position)

                    } else {
                        onFinished.invoke(type, null, position)
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                    onFinished.invoke(type, null, position)
                }
            })
    }

}